package com.zhang.util;

import com.zhang.exception.ServiceException;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static com.zhang.common.Constant.BASIC_PATH;

/**
 * User: 张
 * Date: 2024-11-07
 * Time: 18:30
 * Description:
 */
@Component
public class FileHandleUtils {
    List<String> fileNameList;
    public List<String> fileUpload(MultipartFile[] filesUpload) {
        fileNameList = new ArrayList<>();
        for (MultipartFile file : filesUpload) {
            String fileName = file.getOriginalFilename();
            fileName = UUID.randomUUID() + "_" + fileName;
            File filePath = new File(BASIC_PATH);
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            try {
                file.transferTo(new File(BASIC_PATH + fileName));
                fileNameList.add(BASIC_PATH + fileName);
            } catch (IOException e) {
                throw new ServiceException("文件上传失败");
            }
        }
        return fileNameList;
    }

    public ResponseEntity<byte[]> fileDownload(String filename) {
        //创建该文件对象
        File file = new File(BASIC_PATH + File.separator +filename);
        //设置响应头
        HttpHeaders headers = new HttpHeaders();
        //通知浏览器以下载方式打开
        headers.setContentDispositionFormData("attachment",filename);
        //定义以流的形式下载返回文件数据
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
            return new ResponseEntity<>(FileUtils.readFileToByteArray(file),
                    headers, HttpStatus.OK);
        }
        catch (Exception e) {
            String message = "文件下载失败";
            return new ResponseEntity<byte[]>(message.getBytes(),
                    HttpStatus.EXPECTATION_FAILED);
        }
    }
}
